home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6587 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: erich.triumf.ca!bennett
  2. From: bennett@erich.triumf.ca (P.Bennett)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: I need some help re: scanf, getchar
  5. Date: 16 Feb 1996 22:20 PST
  6. Organization: TRIUMF: Tri-University Meson Facility
  7. Distribution: world
  8. Message-ID: <16FEB199622201908@erich.triumf.ca>
  9. References: <4g3h6g$9ri@nkosi.well.com>
  10. NNTP-Posting-Host: erich.triumf.ca
  11. News-Software: VAX/VMS VNEWS 1.50    
  12.  
  13. In article <4g3h6g$9ri@nkosi.well.com>, rickyarm@well.com () writes...
  14. >Hello there,
  15. >My name is Rick Armanino and I am having some trouble with my program
  16. >for a class that I am taking.  Can someone help with these problems??
  17. >1.  the first time through the do/while loop runs smooth; user enters
  18. >1 for entering new accounts finishes then the loop displays the menu
  19. >again but getchar() does not wait for the users input on the second
  20. >time around and goes straight to the default of the switch.  WHY AND
  21. >WHERE IS GETCHAR GETING ITS INPUT FROM?
  22.  
  23. scanf() is a poor function to use for direct user input.  It is usually much
  24. better to use fgets(), then sscanf(), atoi(), or other things.
  25.  
  26. As you have found, scanf() leaves a '\n' in the input buffer.  If you just use
  27. scanf() this isn't a problem because the next scanf() will just eat the first
  28. '\n' it sees, then get the data you want.  If you mix scanf() with getchar(),
  29. getchar() will see the left-over '\n' as a whole line and the getchar() will
  30. _appear_ to be missed.
  31.  
  32. Another problem with scanf() occurs when it is expecting a number, and the user
  33. enters a letter - scanf() will look at the letter, see it doesn't meet the
  34. input spec, and put it back in the input buffer - you can loop all day trying
  35. to get correct input, and scanf() will keep looking at the same bad char, and
  36. rejecting it.
  37.  
  38. If you use fgets(), you can easily check for valid input, and more easily
  39. recover from input errors (but remember that fgets() leaves an '\n' on the end
  40. of the input string - in some situations you will have to get rid of it before
  41. using the string.)
  42.  
  43.  
  44. Peter Bennett VE7CEI                | Vessels shall be deemed to be in sight
  45. Internet: bennett@triumf.ca         | of one another only when one can be
  46. Packet: ve7cei@ve7kit.#vanc.bc.ca   | observed visually from the other
  47. TRIUMF, Vancouver, B.C., Canada     |                          ColRegs 3(k)
  48. GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
  49.  
  50.